package de.koller.pulsar.scene.cluster;

import de.koller.aframe.util.resource.IOLoader;
import de.koller.oceanFramework.gl.util.RasterManager;
import de.koller.oceanFramework.util.ColorIntUtil;
import de.koller.pulsar.PNode;
import de.koller.pulsar.scene.IScene;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class ClusterScene extends PNode implements IScene {
	public final Random RND = new Random();
	public final int WIDTH = 1000, HEIGHT = 1000;
	public static final int DETAILS = 4;
	
	private RasterManager raster = new RasterManager( WIDTH, HEIGHT );		
	private final AtomicInteger count = new AtomicInteger( 0 );
	
	@Override
	protected void init() {
		super.init();

	}	
	
	@Override
	protected void update( int elapsedTime ) {
		super.update( elapsedTime );
	
		raster.clear( 0xff000000 );
						
		ExecutorService s = Executors.newFixedThreadPool( 8 );
		
		final int workerNumber = 1;
		int w = WIDTH / workerNumber;
		for( int i = 0; i < workerNumber; i++ ) {
			SubFrame sf = new SubFrame( w*i, w );
			s.execute( sf );
		}
		
		try {
			s.shutdown();
			s.awaitTermination( 1, TimeUnit.DAYS );
		} catch ( InterruptedException ex ) {}
			
		proot.setSceneFrame( IOLoader.create( raster ) );
	}

	private class SubFrame implements Runnable {
		
		private final int xStart, wCalc;

		public SubFrame( int xStart, int wCalc ) {
			this.xStart = xStart;
			this.wCalc = wCalc;
		}

		@Override
		public void run() {
			for( int x = xStart; x < xStart + wCalc; x++ ) {
				for( int y = 0; y < raster.getHeight(); y++ ) {
				
					int r = 0, g = 0, b = 0;

					for( int sx = 0; sx < DETAILS; sx++ ) {
						for( int sy = 0; sy < raster.getHeight(); sy++ ) {

							float f = RND.nextFloat();
							if( f < 0.1f / 10f ) {
								r += 0xff;
								g += 0xff;
								b += 0xff;
							}


						}
					}

					r /= DETAILS*DETAILS;
					g /= DETAILS*DETAILS;
					b /= DETAILS*DETAILS;
					raster.setPixel( ColorIntUtil.getIntColor( 0xff, r, g, b ), x, y );
				}

				int c = count.incrementAndGet();
				System.out.println( x + " / " + raster.getWidth() + " (" + + c + ")" );
			}
			
		}
		
	}
	
}
